package org.example.B1;
import com.github.oxo42.stateless4j.StateMachine;
import com.github.oxo42.stateless4j.StateMachineConfig;


public class Heater {

    private GuardCondition guardCondition = new GuardCondition();
    private StateMachine<State, Event> stateMachine;

    public Heater() {
        init();
    }

    public void init() {

        //初始状态有水
        guardCondition.setEmpty(false);
        // 创建状态机配置
        StateMachineConfig<State, Event> config = new StateMachineConfig<>();

        /**
         * 定义状态转换规则
         */
        config.configure(State.OFF)
                /**
                 *当 Event.Night 发生时(即时间来到23点之后)，允许从当前状态转换到 State.SLEEP，并执行 new EnterSleepAction()。
                 */
                .permit(Event.Night,State.SLEEP,new EnterSleepAction())
                /**
                 *当 Event.turnOn 发生时，并且 guardCondition.hasWater() 条件为真时，
                 允许从当前状态转换到 State.ON，并执行 new StartHeaterAction()。
                 */
                .permitIf(Event.TemperatureBelow20, State.ON, guardCondition.hasWater(),new StartHeaterAction())
                /**
                 当 Event.turnOn 发生，并且 guardCondition.isEmpty_or_temperature_le_100()条件为真时，
                 忽略该事件，不进行状态转换。
                 */
                .ignoreIf(Event.TemperatureBelow20, guardCondition.isEmpty())
                .ignore(Event.Morning)
                .ignore(Event.TemperatureTo100)
                .ignore(Event.BurnOut);



        config.configure(State.ON)
                .permit(Event.Night,State.SLEEP, new EnterSleepAction())
                .permit(Event.TemperatureTo100,State.OFF,new StopHeaterAction())
                .permit(Event.BurnOut, State.BURNING_OUT,new WeixiuAction())
                .ignore(Event.Morning)
                .ignore(Event.TemperatureBelow20);



        config.configure(State.SLEEP)
                .permit(Event.Morning,State.OFF,new EndSleepAction())
                .ignore(Event.TemperatureTo100)
                .ignore(Event.TemperatureBelow20)
                .ignore(Event.Night)
                .ignore(Event.BurnOut);

        config.configure(State.BURNING_OUT)
                .ignore(Event.TemperatureTo100)
                .ignore(Event.TemperatureBelow20)
                .ignore(Event.Night)
                .ignore(Event.Morning)
                .ignore(Event.BurnOut);
        // 创建状态机实例
        stateMachine = new StateMachine<>(State.OFF, config);
    }

    public void setEmptyWater(boolean empty) {
        this.guardCondition.setEmpty(empty);
    }

    public void fire(Event event) {
        this.stateMachine.fire(event);
    }

    public State getCurrentState() {
        return this.stateMachine.getState();
    }
    public void printCurrentState() {
        System.out.println("当前状态: " + stateMachine.getState());
    }

}

